package controller

import (
	"dsc-server/domain/dto"
	"dsc-server/pkg/model"
	"dsc-server/pkg/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GroupController API分组控制器
type GroupController struct {
	BaseController
	DB           *gorm.DB
	GroupService *service.GroupService
}

// NewGroupController 创建GroupController实例
func NewGroupController(db *gorm.DB) *GroupController {
	return &GroupController{
		DB:           db,
		GroupService: service.NewGroupService(db),
	}
}

// Create 创建API分组
func (ctrl *GroupController) Create(c *gin.Context) {
	var group model.ApiGroup
	if err := c.ShouldBind(&group); err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "参数绑定失败"))
		return
	}

	result := ctrl.GroupService.Insert(&group)
	c.JSON(http.StatusOK, result)
}

// Delete 删除API分组
func (ctrl *GroupController) Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "ID参数错误"))
		return
	}

	result := ctrl.GroupService.DeleteById(uint(id))
	c.JSON(http.StatusOK, result)
}

// GetAll 获取所有API分组
func (ctrl *GroupController) GetAll(c *gin.Context) {
	groups, err := ctrl.GroupService.GetAll()
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "获取分组失败"))
		return
	}

	c.JSON(http.StatusOK, groups)
}
